package com.alipay.rebate.shop.service.admin.impl;

import com.alipay.rebate.shop.configuration.shiro.token.AdminToken;
import com.alipay.rebate.shop.constants.CommonConstant;
import com.alipay.rebate.shop.constants.OrdersConstant;
import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.constants.UserContant;
import com.alipay.rebate.shop.core.AbstractService;
import com.alipay.rebate.shop.dao.mapper.*;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.helper.SevenDayinnerNumberHelper;
import com.alipay.rebate.shop.model.AdminUser;
import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.model.UserIncome;
import com.alipay.rebate.shop.pojo.AdminIndexRsp;
import com.alipay.rebate.shop.pojo.adminindex.SevenDayInnerNumber;
import com.alipay.rebate.shop.pojo.user.TokenRsp;
import com.alipay.rebate.shop.pojo.user.admin.AdminUserObjRsp;
import com.alipay.rebate.shop.pojo.user.admin.AdminUserRewordReq;
import com.alipay.rebate.shop.pojo.user.customer.UserDto;
import com.alipay.rebate.shop.service.admin.AdminUserService;
import com.alipay.rebate.shop.utils.DateUtil;
import com.alipay.rebate.shop.utils.IpUtil;
import com.alipay.rebate.shop.utils.JwtUtils;
import com.alipay.rebate.shop.utils.ListUtil;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by CodeGenerator on 2019/12/08.
 */
@Service
@Transactional
public class AdminUserServiceImpl extends AbstractService<AdminUser> implements AdminUserService {

    private Logger logger = LoggerFactory.getLogger(AdminUserServiceImpl.class);

    @Resource
    private AdminUserMapper adminUserMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private WithDrawMapper withDrawMapper;
    @Resource
    private SevenDayinnerNumberHelper sevenDayinnerNumberHelper;
    @Resource
    private UserIncomeMapper userIncomeMapper;
    @Resource
    PddOrdersMapper pddOrdersMapper;
    @Resource
    JdOrdersMapper jdOrdersMapper;

    //TODO(多余)
    @Override
    public Long insert(User user) {
        return null;
    }

    //TODO(多余)
    @Override
    public int delete(Long id) {
        return 0;
    }

    //TODO(多余)
    @Override
    public int update(User user) {
        return 0;
    }

    //TODO(多余)
    @Override
    public User get(Long id) {
        return null;
    }


    @Override
    public List<String> getUserRoles(Long userId) {
        return null;
    }

    @Override
    public UserDto getJwtTokenInfo(String id) {
        UserDto userDto = adminUserMapper.selectUserDtoInfoById(Long.valueOf(id));
        userDto.setSalt(CommonConstant.JWT_SALT);
        return userDto;
    }

    @Override
    public void addNewAdminUser(AdminUser adminUser) {
        AdminUser dbUser = adminUserMapper.selectUserByAccount(adminUser.getUserAccount());
        if(dbUser != null){
            throw new BusinessException("账号已存在", StatusCode.USER_ALREADY_EXISTS);
        }
        adminUserMapper.insertSelective(adminUser);
    }

    @Override
    public void updateAdminUser(AdminUser adminUser) {
        AdminUser dbUser = adminUserMapper.selectUserByAccount(adminUser.getUserAccount());
        if(dbUser != null && !dbUser.getId().equals(adminUser.getId())){
            throw new BusinessException("账号已存在", StatusCode.USER_ALREADY_EXISTS);
        }
        adminUserMapper.updateByPrimaryKeySelective(adminUser);
    }

    @Override
    public List<AdminUserObjRsp> selectAllWithGroupMsg(String account) {
        return adminUserMapper.selectAllWithGroupMsg(account);
    }

    @Override
    public UserDto getUserDtoInfoForAdminLogin(String phone) {
        return adminUserMapper.selectUserDtoInfoForAdminLogin(phone);
    }

    @Transactional
    @Override
    public AdminUserObjRsp adminLogin(
        UserDto loginInfo,
        HttpServletRequest request,
        HttpServletResponse response,
        Subject subject)
    {

        // 生成WeixinToken
        AdminToken adminToken = new AdminToken();
        adminToken.setUsername(loginInfo.getAccount());
        adminToken.setPassword(loginInfo.getPassword());
        logger.debug("Login AdminAccountToken is : {}", adminToken);
        // 登陆
        subject.login(adminToken);
        logger.debug("Shiro Login success");
        // 生成token并且设置到header中
        UserDto user = (UserDto) subject.getPrincipal();
        logger.debug("Login getPrincipal is : {}", user);

        String accessToken = JwtUtils.sign(
            String.valueOf(user.getUserId()),
            UserContant.PC_LOGIN_TYPE,
            CommonConstant.JWT_SALT,
            //一天过期
            CommonConstant.ACCESS_TOKEN_EXPIRE_TIME_ONEDAY);

        String refreshToken = JwtUtils.sign(
            String.valueOf(user.getUserId()),
            UserContant.PC_LOGIN_TYPE,
            CommonConstant.JWT_SALT,
            //一天过期
            CommonConstant.REFRESH_TOKEN_EXPIRE_TIME_ONEDAY);

        logger.debug("PC Login accessToken is : {}", accessToken);
        logger.debug("PC Login refreshToken is : {}", refreshToken);
        logger.debug("userDto is : {}", user);

        response.setHeader(CommonConstant.ACCESS_HEADER_KEY, accessToken);
        response.setHeader(CommonConstant.AUTH_HEADER_KEY, accessToken);
        response.setHeader(CommonConstant.REFRESH_HEADER_KEY, refreshToken);

        updateUserLoginInfo(request,user.getUserId());

        return adminUserMapper.selectUserWithGroupMsg(user.getUserId());
    }

    private void updateUserLoginInfo(HttpServletRequest request, Long id){
        Date date = new Date();
        String ip = IpUtil.getIpAddress(request);
        AdminUser adminUser = new AdminUser();
        adminUser.setLastLoginIp(ip);
        adminUser.setNewlyLoginIp(ip);
        adminUser.setLastLoginTime(date);
        adminUser.setNewlyLoginTime(date);
        adminUser.setId(id);
        adminUserMapper.updateByPrimaryKeySelective(adminUser);
    }

    @Override
    public AdminIndexRsp selectIndexInfo() {

        AdminIndexRsp adminIndexRsp1 = userMapper.selectAdminIndexInfo();
        AdminIndexRsp adminIndexRsp2 = ordersMapper.selectIndexInfo();
        List<Orders> orders = ordersMapper.selectCurDayOrder();
        Integer wCount = withDrawMapper.selectCurdayCount();
        Integer withDrawCount = withDrawMapper.selectNotHandleWithDrawCount();
        // 查找昨日付款订单数和昨日结算订单数
        int paymentOrderQuantity = ordersMapper.selectPaymentOrderQuantity(DateUtil.getBeginDayOfYesterday(), DateUtil.getEndDayOfYesterDay());
        int settlementOrdersQuantity = ordersMapper.selectSettlementOrdersQuantity(DateUtil.getBeginDayOfYesterday(), DateUtil.getEndDayOfYesterDay());
        List<SevenDayInnerNumber> sevenDayInnerNumber = sevenDayinnerNumberHelper.getSevenDayInnerNumber();

        // pddOrders
        int totalPddOrdersNum = pddOrdersMapper.getTotalPddOrdersNum();
        int todayPaidOrdersNum = pddOrdersMapper.getTodayPaidOrdersNum();
        int yesterdayPaidOrdersNum = pddOrdersMapper.getYesterdayPaidOrdersNum(DateUtil.getYesterday());
        BigDecimal totalCommission = pddOrdersMapper.getTotalCommission();
        BigDecimal todayCommissionFee = pddOrdersMapper.getTodayCommissionFee();
        BigDecimal yesterdayCommissionFee = pddOrdersMapper.getYesterdayCommissionFee(DateUtil.getYesterday());
        // jdOrders
        int totalJdOrdersNum = jdOrdersMapper.getTotalJdOrdersNum();
        int todayPaidOrdersNum1 = jdOrdersMapper.getTodayPaidOrdersNum();
        int yesterdayPaidJdOrdersNum = jdOrdersMapper.getYesterdayPaidOrdersNum(DateUtil.getYesterday());
        BigDecimal totalJdCommission = jdOrdersMapper.getTotalCommission();
        BigDecimal todayJdCommissionFee = jdOrdersMapper.getTodayCommissionFee();
        BigDecimal yesterdayJdCommissionFee = jdOrdersMapper.getYesterdayCommissionFee(DateUtil.getYesterday());


        AdminIndexRsp rsp = new AdminIndexRsp();
        rsp.setTotalUserNumber(adminIndexRsp1.getTotalUserNumber());
        rsp.setTodayRegisterUserNumber(adminIndexRsp1.getTodayRegisterUserNumber());
        rsp.setYesterdayRegisterUserNumber(adminIndexRsp1.getYesterdayRegisterUserNumber());
        rsp.setTotalOrderNumber(adminIndexRsp2.getTotalOrderNumber());
        rsp.setTotalCm(adminIndexRsp2.getTotalCm().setScale(2,BigDecimal.ROUND_DOWN));
        rsp.setTodayWithDrawNumber(wCount);

        int todayPaidOrderNum1 = ordersMapper.selectTodayPaidOrderNum();
        int todayPaidOrderNum = 0 ;
        int todayAcOrderNum = 0;
        BigDecimal todayPaidCm = new BigDecimal(0.00);
        BigDecimal todayACCm = new BigDecimal(0.00);
        if(!ListUtil.isEmptyList(orders)){
           for(Orders order: orders){
               if(OrdersConstant.PAID_STATUS.equals(order.getTkStatus())){
                   todayPaidOrderNum ++;
                   todayPaidCm = todayPaidCm.add(order.getPubSharePreFee());
               }
               if(OrdersConstant.ACCOUNTING_STATUS.equals(order.getTkStatus()) ||
                   OrdersConstant.COMPLETE_STATUS.equals(order.getTkStatus())
               ){
                   todayAcOrderNum ++;
                   todayACCm = todayACCm.add(order.getPubSharePreFee());
               }
           }
        }
        rsp.setTodayPaidOrderNumber(todayPaidOrderNum1);
        todayPaidCm = todayPaidCm.setScale(2,BigDecimal.ROUND_DOWN);
        BigDecimal todayPaidCm1 = ordersMapper.getTodayPaidCm();
        rsp.setTodayPaidCm(todayPaidCm1);
        rsp.setTodayACOrderNumber(todayAcOrderNum);
        todayACCm = todayACCm.setScale(2,BigDecimal.ROUND_DOWN);
        rsp.setTodayACCm(todayACCm);

        // 设置昨日付款订单数和结算订单数
        rsp.setYesterDayPaidCount(paymentOrderQuantity);
        rsp.setYesterDayACCount(settlementOrdersQuantity);
        rsp.setCurrentNotHanleWithdrawNumber(withDrawCount);
        rsp.setSevenDayInnerNumber(sevenDayInnerNumber);
        rsp.setTotalPddOrdersNum(totalPddOrdersNum);
        rsp.setTodayPaidPddOrderNum(todayPaidOrdersNum);
        rsp.setYesterdayPaidPddOrdersNmu(yesterdayPaidOrdersNum);
        rsp.setPddOrdersTotalCommission(totalCommission);
        rsp.setYesterdayPaidPddOrdersCommissionFee(yesterdayCommissionFee);
        rsp.setTodayPaidPddOrdersCommissionFee(todayCommissionFee);
        rsp.setTotalJdOrdersNum(totalJdOrdersNum);
        rsp.setTodayPaidjdOrderNum(todayPaidOrdersNum1);
        rsp.setYesterdayPaidJdOrdersNmu(yesterdayPaidJdOrdersNum);
        rsp.setJdOrdersTotalCommission(totalJdCommission);
        rsp.setTodayPaidJdOrdersCommissionFee(todayJdCommissionFee);
        rsp.setYesterdayPaidJdOrdersCommissionFee(yesterdayJdCommissionFee);

        return rsp;
    }

    @Override
    public TokenRsp getNewToken(long userId) {
        String accessToken = JwtUtils.sign(
            String.valueOf(userId), UserContant.PC_LOGIN_TYPE,
            CommonConstant.JWT_SALT,
            CommonConstant.ACCESS_TOKEN_EXPIRE_TIME);
        String refreshToken = JwtUtils.sign(
            String.valueOf(userId), UserContant.PC_LOGIN_TYPE,
            CommonConstant.JWT_SALT,
            CommonConstant.ACCESS_TOKEN_EXPIRE_TIME);
        TokenRsp tokenRsp = new TokenRsp();
        tokenRsp.setAccess_token(accessToken);
        tokenRsp.setRefresh_token(refreshToken);
        return tokenRsp;
    }


    @Override
    public int rewordUser(AdminUserRewordReq req,int type){

        logger.debug("req is : {}",req);
        logger.debug("type is : {}",type);
        User user = new User();
        UserIncome userIncome = new UserIncome();

        user.setUserId(req.getUserId());
        if (type == 0) {
            //奖励金额
            user.setUserAmount(req.getReword());
            userIncome.setMoney(req.getReword());
            userIncome.setAwardType(1);
        }
        if (type == 1) {
            //奖励集分宝
            BigDecimal userIntgeralTreasure = new BigDecimal(req.getReword().longValue());
            logger.debug("userIntgeralTreasure is : {}",userIntgeralTreasure);
            BigDecimal bigDecimal1 = new BigDecimal(100.00);
            BigDecimal divide = userIntgeralTreasure.divide(bigDecimal1);
            user.setUserIntgeralTreasure(req.getReword().longValue());
            userIncome.setMoney(divide);
            userIncome.setAwardType(2);
        }
        if (type == 2) {
            //奖励积分
            user.setUserIntgeral(req.getReword().longValue());
            userIncome.setIntgeralNum(req.getReword().longValue());
            userIncome.setAwardType(3);
        }

        logger.debug("user is : {}",user);
        int result = userMapper.updateUserByUserId(user);


        userIncome.setUserId(req.getUserId());
        userIncome.setType(12);
        userIncome.setStatus(1);
        userIncome.setRemarks(req.getRemarks());
        userIncome.setCreateTime(DateUtil.getNowStr());
        userIncome.setUpdateTime(DateUtil.getNowStr());
        logger.debug("userIncome is : {}",userIncome);
        userIncomeMapper.insert(userIncome);

        return result;
    }

}
